<template>
  <el-row>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ name: 'dashboard' }">控制台</el-breadcrumb-item>
      <el-breadcrumb-item>发放优惠券</el-breadcrumb-item>
    </el-breadcrumb>
    <blank />

    <el-form :model="ticket" ref="ticket" label-width="100px" class="" @keyup.enter.native="submitForm('ticket')">

      <el-form-item label="用户">
        <el-autocomplete
          v-model="nickname"
          :fetch-suggestions="querySearch"
          :trigger-on-focus="false"
          style="width:100%"
          placeholder="输入昵称或者OpenId查询，支持模糊查询"
          @select="handleSelect"
        ></el-autocomplete>
      </el-form-item>

      <el-form-item label="标题" prop="Title" :rules="[
        { required: true, message: '标题不能为空'},
        { min: 1, max: 20, message: '长度在 1 到 20 个字符' }]">
        <el-input v-model="ticket.Title"></el-input>
      </el-form-item>

      <el-form-item label="优惠券说明" prop="Detail" :rules="[
        { required: true, message: '说明不能为空'},
        { min: 1, max: 300, message: '长度在 1 到 300 个字符' }]">
        <el-input v-model="ticket.Detail"></el-input>
      </el-form-item>

      <el-form-item label="价值" prop="Worth" :rules="[
        { required: true, message: '价值不能为空'},
        { type: 'number', message: '价值必须为数字值'} ]">
        <el-input v-model.number="ticket.Worth"></el-input>
      </el-form-item>
      
      <el-form-item label="过期时间" prop="Expired" :rules="[{ required: true, message: '过期时间不能为空'}]">
        <el-date-picker
          v-model="ticket.Expired"
          type="date"
          placeholder="选择日期"
          :picker-options="pickerOptions0">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="使用场景">
        <el-checkbox-group v-model="sceneList" v-loading="loading">
          <div class="scene-tip">若不选，默认为无限制使用；选择之后，只能在对应的下单场景使用</div>
          <div v-for="(group, key, index) in targets" :key="group.key">
            <el-tag :type="key | lable">{{ group.desc }}</el-tag>
            <el-checkbox v-for="(target, key, index) in group.data" :key="target.Id" :label="target.Code" :disabled="target.Item | sceneDisabled">{{ target.Target  | scene(target.Item) }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item>
        <el-button :loading="loadingState" type="primary" @click="submitForm('ticket')">发送</el-button>
        <el-button @click="resetForm('ticket')">重置</el-button>
        <el-button @click="dialogVisible = true">查询用户</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="查询用户" v-model="dialogVisible">
      <el-input placeholder="请输入内容" v-model="searchKey">
        <el-button slot="append" icon="search" @click="searchUsers"></el-button>
      </el-input>
      <blank lines="2" />
      <el-table :data="users">
        <el-table-column property="OpenId" label="OpenId" width="150"></el-table-column>
        <el-table-column property="NickName" label="昵称" width="200"></el-table-column>
        <el-table-column label="头像" show-overflow-tooltip align="center">
          <template scope="scope">
            <img :src="scope.row.AvatarUrl" class="avatar" />
          </template>
        </el-table-column>
        <el-table-column label="地点" show-overflow-tooltip align="center">
          <template scope="scope">
            {{ scope.row.Country }}
            {{ scope.row.Province }}
            {{ scope.row.City }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </el-row>
</template>

<script>
import blank from '@/components/Blank'
import ax, { errhandler } from '@/api/_axios-config'
import * as apis from '@/api/_api'
import { Message } from 'element-ui'
import router from '@/router'

export default {
  name: 'ticket',
  data () {
    return {
      ticket: {
        OpenId: '',
        Title: '',
        Worth: '',
        Expired: '',
        IsUsed: false,
        Scene: '',
        Detail: ''
      },
      pickerOptions0: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      openid: '',
      loadingState: false,
      dialogVisible: false,
      users: [],
      searchKey: '',
      nickname: '',
      targets: [],
      sceneList: [],
      loading: true
    }
  },
  filters: {
    scene: function (target, item) {
      if (item === 1) {
        return '开荒保洁'
      } else if (item === 3) {
        return '地毯清洗'
      } else if (item === 2) {
        return '玻璃清洗'
      } else if (item === 7) {
        return '定制服务'
      } else {
        return target
      }
    },
    sceneDisabled: function (item) {
      if (item === 1 || item === 2 || item === 3 || item === 7) {
        return true
      } else {
        return false
      }
    },
    lable: function (key) {
      if (key % 2 === 0) {
        return ''
      } else {
        return 'primary'
      }
    }
  },
  methods: {
    searchUsers () {
      if (this.searchKey) {
        ax.get(apis.QUERY_USER_BY_NICKNAME_OPENID, {params: {nicknameOrOpenId: this.searchKey}}).then(response => {
          let result = response.data
          if (result.BoolStatus) {
            this.users = result.Data
          } else {
            Message.error('无此用户')
          }
        }).catch(err => {
          errhandler(err)
        })
      }
    },
    querySearch (queryString, cb) {
      ax.get(apis.QUERY_USER_BY_NICKNAME_OPENID, {params: {nicknameOrOpenId: queryString}}).then(response => {
        let result = response.data
        if (result.BoolStatus) {
          for (let i = 0; i < result.Data.length; i++) {
            result.Data[i]['value'] = result.Data[i]['NickName']
          }
          cb(result.Data)
        } else {
          Message.error('无此用户')
        }
      }).catch(err => {
        errhandler(err)
      })
    },
    handleSelect (item) {
      this.ticket['OpenId'] = item['OpenId']
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('请确认优惠券数据无误，谨慎操作', '提示', {
            confirmButtonText: '确认发送',
            cancelButtonText: '返回修改',
            type: 'warning'
          }).then(() => {
            this.loadingState = true
            if (this.ticket['OpenId'] === '' || this.ticket['OpenId'] === null) {
              Message.success('未正确选择用户')
              this.loadingState = false
              return
            }
            if (this.sceneList !== null && this.sceneList.length > 0) {
              this.ticket.Scene = ''
              for (let i = 0; i < this.sceneList.length; i++) {
                this.ticket.Scene += this.sceneList[i] + ','
              }
              this.ticket.Scene = this.ticket.Scene.substring(0, this.ticket.Scene.length - 1)
            }
            ax.post(apis.SEND_TICKET, this.ticket).then(response => {
              let result = response.data
              if (result.BoolStatus) {
                this.$alert('发送成功', '结果', {
                  confirmButtonText: '确定',
                  callback: action => {
                    router.go(0)
                  }
                })
              } else {
                Message.error(result.Message)
              }
              this.loadingState = false
            }, err => {
              this.loadingState = false
              errhandler(err)
            })
          }).catch(() => {
            Message.info('发送已取消')
          })
        } else {
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  },
  components: { blank },
  created: function () {
    ax.get(apis.ALL_TARGET).then(response => {
      let result = response.data
      if (result.BoolStatus) {
        let targets = result.Data
        let data = []
        let temp = null
        let group = []
        let count = 0
        for (let i = 0; i < targets.length; i++) {
          if (temp == null) {
            temp = targets[i]
            group.push(targets[i])
          } else {
            if (temp.Item === targets[i].Item) {
              temp = targets[i]
              group.push(targets[i])
            } else {
              let desc = ''
              switch (temp.Item) {
                case 0:
                  desc = '日常保洁'
                  break
                case 1:
                  desc = '开荒保洁'
                  break
                case 2:
                  desc = '玻璃清洗'
                  break
                case 3:
                  desc = '地毯清洗'
                  break
                case 4:
                  desc = '空调清洗'
                  break
                case 5:
                  desc = '油烟机清洗'
                  break
                case 6:
                  desc = '包月服务'
                  break
                case 7:
                  desc = '定制服务'
                  break
              }
              data.push({key: count, desc: desc, data: group})
              group = [targets[i]]
              count++
              temp = targets[i]
            }
          }
        }
        this.targets = data
      } else {
        Message.error(result.Message)
      }
      this.loading = false
    }).catch(err => {
      errhandler(err)
      this.loading = false
    })
  }
}
</script>

<style lang="stylus">
  .avatar
    width 100px
    height 100px
  .scene-tip
    color #d6292e
    font-weight bold
</style>
